<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <PageTools ref="pageTs" @query="querySome">
          <template #before>
            <el-button type="primary" dialog-visible plain @click="addFn">添加房产</el-button>
          </template>
          <template #after>
            <el-select v-model="form.category" placeholder="请选择筛选的分类" @change="categoryAll">
              <el-option label="全部分类" value="" />
              <el-option v-for="i in myClass" :key="i.id" :label="i.title" :value="i.id" />
            </el-select>
            <el-select v-model="agentvalue" placeholder="请选择筛选的经纪" @change="agentAll">
              <el-option label="全部经纪" value="" />
              <el-option v-for="i in agent" :key="i.id" :label="i.name" :value="i.id" />
            </el-select>
          </template>
        </PageTools>
      </el-card>
      <el-card>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column
            prop="image"
            label="封面"
            align="center"
          >
            <template v-slot="{row}">
              <img :src="row.image" alt="" class="tableImg">
            </template>
          </el-table-column>
          <el-table-column
            prop="title"
            label="标题"
            align="center"
          />
          <el-table-column
            prop="tags"
            label="标签"
            align="center"
          >
            <!-- <el-tag
              v-for="tag in dynamicTags"
              :key="tag"
              type="success"
            >
              {{ tag }}
            </el-tag> -->
            <template v-slot="{row}">
              <el-row v-for="tag in row.tags" :key="tag">
                <el-tag>{{ tag }}</el-tag>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="地址"
            align="center"
          />
          <el-table-column
            prop="category.title"
            label="分类"
            align="center"
          />
          <el-table-column
            prop="agent.name"
            label="经纪"
            align="center"
          />
          <el-table-column
            prop="price"
            label="价格"
            align="center"
          />
          <el-table-column
            prop="desc"
            label="介绍"
            align="center"
          />
          <el-table-column
            prop="photos"
            label="图片"
            align="center"
          >
            <template v-slot="{row}">
              <!-- <el-row v-for="item in row.photos" :key="item">
                <img :src="item" alt="" style="height:200px;width:100px;object-fit:cover;">
              </el-row> -->

              <el-row v-for="item in row.photos" :key="item.id">
                <img :src="item" alt="" class="tableImg">
              </el-row>
            </template>

          </el-table-column>

          <el-table-column
            prop="date"
            label="操作"
            align="center"
            width="150"
          >
            <template v-slot="{row}">
              <el-button type="primary" plain size="small" @click="editFn(row.id)">编辑</el-button>
              <el-button type="danger" plain size="small" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalhouse"
            :page-size="pages._limit"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>

      <!-- dialog框 -->
      <el-dialog :visible="dialogTableVisible" @close="closeFn">
        <el-form ref="form" v-model="form" :model="form" label-width="120px" :rules="rules">
          <el-form-item label="经纪" prop="agent">
            <el-select v-model="form.agent" placeholder="请选择" style="width:80%">
              <el-option v-for="i in agent" :key="i.id" :label="i.name" :value="i.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="form.category" placeholder="请选择" style="width:80%">
              <el-option v-for="i in myClass" :key="i.id" :label="i.title" :value="i.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" type="text" style="width:80%" />
          </el-form-item>
          <el-form-item label="标签">
            <el-tag
              v-for="tag in dynamicTags"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="saveTagInput"
              v-model="inputValue"
              class="input-new-tag"
              size="small"
              style="width:80%"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
          </el-form-item>
          <div style="display:flex;justify-content:start">
            <el-form-item label="地址">
              <template>
                <div id="app">
                  <el-cascader
                    v-model="form.address"
                    placeholder="请选择地址"
                    size="large"
                    :options="options"
                    style="width: 140px;"
                    @change="handleChange"
                  />
                </div>
              </template>

            </el-form-item>
            <el-input
              v-model="form.address"
              style="width:44%"
            />
          </div>
          <el-form-item label="价格">
            <el-input v-model="form.price" type="text" style="width:80%" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="form.desc" type="textarea" style="width:80%" rows="5" />
          </el-form-item>
          <el-form-item label="内容">
            <quill-editor
              v-model="form.content"
              class="quill-editor"
              style="width:80%"
            />
          </el-form-item>
          <el-form-item label="介绍图片">
            <ImageUpload ref="imgUpload1" :limit="3" />
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
          <el-form-item label="封面">
            <ImageUpload ref="imgUpload" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button plain size="small" @click="closeFn">取 消</el-button>
          <el-button type="primary" plain size="small" @click="confirmFn">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 获取列表数据,添加房产,房产数量，删除数据
import { getPages, addRealEstate, houseNum, delHouse, getHouseById, editHouse } from '@/api/realEstate'
// 获取经纪列表
import { getMangerList } from '@/api/managerList'
import { GetClassfication } from '@/api/Classfications'
// 级联插件
import { regionData, CodeToText } from 'element-china-area-data'

// 获取分类列表

export default {
  data() {
    return {
      condition1: '',
      condition2: '',
      // 房产数量的变量
      totalhouse: 0,
      // dialog框显示隐藏
      dialogTableVisible: false,
      // 数据数组
      tableData: [],
      // 经纪列表
      agent: [],
      agentvalue: '',
      // 表单对象
      form: {
        title: '',
        desc: '',
        image: '',
        agent: '',
        content: '',
        tags: [],
        address: '',
        price: '',
        photos: [],
        category: ''
      },
      // 类别列表
      myClass: [],
      // 标签的属性
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      // 介绍图片属性
      dialogImageUrl: '',
      dialogVisible: false,

      // 级联
      options: regionData,
      // selectedOptions: [],
      // 校验对象
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请填写描述', trigger: 'blur' }

        ]
      },
      // 简单地址
      add: '',
      // 确切的地址
      detailAdd: '',
      // 换页对象
      pages: {
        // 每页显示条目
        _limit: 3,
        _start: 0
      }
    }
  },
  async created() {
    // 渲染表格
    await this.getTableData()
    // 获取经纪数量
    const res = await getMangerList()
    this.agent = res.data
    console.log('经济', res)
    // 获取类别数量
    const result = await GetClassfication()
    this.myClass = result.data
    // 获取房产数量
    // const num = await houseNum()
    // this.totalhouse = num.data
    // console.log('房产数量', this.totalhouse)
    this.homenum()
  },
  methods: {
    categoryAll(value) {
      // console.log(282, value)
      this.condition1 = value
    },
    agentAll(value) {
      this.condition2 = value
    },
    // 筛选
    async querySome() {
      const { data } = await getPages({
        // 展开对象,因为筛选的时候传参要传多几个
        _limit: this.pages._limit,
        // 用短路运算，每输入的时候值为null，输入的时候用输入的值
        title_contains: this.$refs.pageTs.value || null,
        // 经纪，短路运算，
        agent: this.condition2 || null,
        category: this.condition1 || null
      })
      this.tableData = data
      this.homenum()
    },
    // 转化图片路径
    exchangeUrl(photos) {
      photos.forEach(item => {
        this.$refs.imgUpload1.fileList.push({ url: item })
      })
    },
    // 获取房产数量的函数
    async homenum() {
      const num = await houseNum({ title_contains: this.$refs.pageTs.value || null,
        agent: this.condition2 || null,
        category: this.condition1 || null })
      this.totalhouse = num.data
      console.log('房产数量', this.totalhouse)
    },
    // 封装获取列表数据的函数
    async getTableData() {
      const { data } = await getPages({
        // 展开对象,因为筛选的时候传参要传多几个
        ...this.pages
        // 用短路运算，每输入的时候值为null，输入的时候用输入的值
        // title_contains: this.$refs.pageTs.value || null,
        // 经纪，短路运算，
        // agent: this.agentSelect || null
        // category:
      })
      this.tableData = data
      console.log('9/4', this.tableData)
    },
    // 添加按钮
    addFn() {
      this.dialogTableVisible = true
    },
    // 编辑按钮
    async editFn(id) {
      const res = await getHouseById(id)
      this.dialogTableVisible = true
      this.form = {
        ...res.data,
        agent: res.data.agent.id
      }
      this.dynamicTags = this.form.tags
      this.$nextTick(() => {
        this.$refs.imgUpload.fileList = [{ url: this.form.image
        }]
        this.exchangeUrl(res.data.photos)
      })
    },
    // 关闭弹窗
    async closeFn() {
      this.$refs.form.resetFields()
      // 关闭弹窗
      this.dialogTableVisible = false
      this.form = {
        title: '',
        desc: '',
        image: '',
        agent: '',
        content: '',
        tags: [],
        address: '',
        price: '',
        photos: [],
        category: ''
      }
      this.dynamicTags = []
      this.$refs.imgUpload.fileList = []
      this.$refs.imgUpload1.fileList = []
    },
    // 标签方法
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 介绍图片方法
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    // 级联的方法
    handleChange(value) {
      console.log(value)
      // 声明空数组存地址
      const arr = []
      value.forEach(i => {
        arr.push(CodeToText[i])
      })
      // console.log(arr.join('/'))
      this.form.address = arr.join('/')
      // console.log(this.form)
      this.detailAdd = this.form.address
    },
    // 表单确定按钮的事件
    async confirmFn() {
      await this.$refs.form.validate()
      // 将图片列表获取下来
      const fileList = this.$refs.imgUpload.fileList
      // console.log('图片对象', fileList)
      // 声明变量将fileList改造成url
      const data = fileList.map(item => item.url)
      console.log(data, '图片地址')
      // 如果没传头像，就不发请求
      if (this.$refs.imgUpload.fileList.length === 0) {
        this.$message.error('请先上传头像')
        return
      }
      this.form.tags = this.dynamicTags
      // 添加的接口
      if (this.form.id) {
        await editHouse({
          ...this.form,
          image: this.$refs.imgUpload.fileList[0].url,
          photos: (this.$refs.imgUpload1.fileList).map(item => item.url)
        })
        this.$message.success('修改房产信息成功！')
      } else {
        await addRealEstate({
          ...this.form,
          image: this.$refs.imgUpload.fileList[0].url,
          photos: (this.$refs.imgUpload1.fileList).map(item => item.url)
        })
        this.$message.success('添加房产信息成功！')
      }
      // console.log(111, this.form.photos)
      // console.log(222, (this.$refs.imgUpload1.fileList).map(item => item.url))
      this.homenum()
      await this.getTableData()
      this.closeFn()
    },
    // 删除按钮
    delFn(id) {
      this.$confirm('是否确定删除该房产信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delHouse(id)
        if (this.tableData.length === 1 && this.pages._start >= this.pages._limit) {
          this.pages._start -= this.pages._limit
        }
        this.tableData = []
        // 重新渲染
        await this.getTableData()
        this.homenum()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 分页事件
    async currentChange(value) {
      // value是当前页
      this.pages._start = (value - 1) * this.pages._limit
      // this.tableData = []
      await this.getTableData()
    }

  }
}
</script>

<style lang="scss" scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .tableImg {
  width: 178px;
  height: 120px;
  margin-left: -20px;
   /* 图片写死宽高的情况, 控制拉伸效果的样式 */
  object-fit: contain;
   /* object-fit: cover; */
}
.ql-container {
    height: 400px;
  }
/* ::v-deep .imgT{
  width: 185px;
} */
</style>
